-- UIAwakeCrystalPath
-- Created by chendh Nov/30/2016
-- 觉醒雕像晶核产出途径界面

-- UIAwakeCrystalPath继承自Layer
UIAwakeCrystalPath = class("UIAwakeCrystalPath", function()
    return cc.Layer:create();
end);

function UIAwakeCrystalPath.create(petId, tabs)
    return UIAwakeCrystalPath.new(petId, tabs);
end

-- 构造函数
function UIAwakeCrystalPath:ctor(petId, tabs)
    -- 初始化
    self:setName("UIAwakeCrystalPath");
    local node = cc.CSLoader:createNode("layout/item/GainItemPath.csb");
    self:addChild(node);
    self.node = node;
    self.petId = petId;

    -- 当前标签页与上一层相同
    if not tabs then
        tabs = {};
    end
    self.tab = tabs;
    table.insert(self.tab, "crystal");

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    self:initData();

    -- 适配
    self:resize();
end

-- 适配
function UIAwakeCrystalPath:resize()

    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIAwakeCrystalPath:redraw()
    -- 绘制公共模板背景
    self:redrawTemplate();

    -- 重绘物品及描述
    self:redrawItemAndDesc();

    -- 重绘标签页
    self:redrawTabs();
end

-- 绘制标签页
function UIAwakeCrystalPath:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tabs");
    local tabNum = #self.tab;

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));

    for i = 1, tabNum do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 - 210;
        local y = -34;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        if i == tabNum then
            tabImage:loadTexture("images/ui/tab/red.png");
        end
        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        if i == tabNum then
            tabLight:setVisible(true);
        else
            tabLight:setVisible(false);
        end

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");

        tabText:setVisible(false);
        if self.tab[i] == "crystal" then
            tabIcon:loadTexture(getAwakeIconPath("crystal"));
        elseif self.tab[i] == "carving" then
            tabIcon:loadTexture(getAwakeIconPath("carving"));
        else
            tabIcon:loadTexture(getItemIconPath(ItemM.query(self.tab[i][2], "icon")));
        end
        tabIcon:setScale(0.5);

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end
end

-- 绘制公共模板背景
function UIAwakeCrystalPath:redrawTemplate()
    -- 更换公共模板上方2侧的图片
    local bgType1 = findChildByName(self.node, "CT/template/bg_type");
    local bgType2 = findChildByName(self.node, "CT/template/bg_type2");
    bgType1:loadTexture(getTitleBgIconPath("upgrade"));
    bgType2:loadTexture(getTitleBgIconPath("upgrade"));

    -- 绘制标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    local subHeadLabel = findChildByName(self.node, "CT/template/subhead");

    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("awake_crystal_title"));

    -- 副标题
    local itemAmount = ItemM.getAmount(ME.user, self.classId);
    TextStyleM.setSubheadStyle(subHeadLabel);
    subHeadLabel:setString(getLocStr("awake_crystal_subhead"));
end

-- 重绘食物信息
function UIAwakeCrystalPath:redrawItemAndDesc()
    local item = findChildByName(self.node, "CT/item");

    -- 物品图标
    local iconImg = findChildByName(item, "icon");
    iconImg:loadTexture(getAwakeIconPath("crystals"));

    -- 物品星级
    local starNode = findChildByName(item, "star_node");
    starNode:setVisible(false);

    -- 物品的背景框
    local frameImage = findChildByName(item, "bg");
    frameImage:loadTexture(getFrameBgIconPath("rank", 1));
end

-- 注册标签页点击回调
function UIAwakeCrystalPath:registerTabTouchEvent(node)
    local tabImage = node:getChildByName("tab");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            if node.index < #self.tab then
                UIMgr.getCurrentScene():removeFormByName("UIAwakeCrystalPath");
            end
        end
    end

    tabImage:addTouchEventListener(onClick);
end

-- 注册点击事件
function UIAwakeCrystalPath:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIAwakeCrystalPath");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end


function UIAwakeCrystalPath:registerEventCallback()
    -- 注册获得焦点的回调
    EventMgr.register("UIAwakeCrystalPath", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIAwakeCrystalPath" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIAwakeCrystalPath界面析构清理");
            EventMgr.removeAll("UIAwakeCrystalPath");
        elseif eventType == "enter" then

        end
    end);
end

-- 初始化奖励列表
function UIAwakeCrystalPath:initData()
    local scrollview = findChildByName(self.node, "CT/scroll_view");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/item/PathInfo.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 建造雕像消耗的晶核列表
    local crystalCost = AwakeM.query(self.petId, "crystal_cost");

    -- 左边距
    local leftMargin = 1;

    -- 行间距
    local gap = 0;
    local widgetHeight = 61;
    local totalNum = #crystalCost;
    local startHeight = 10;

    --计算总高度
    local totalHeight = math.max(totalNum * (widgetHeight + gap), scrollview:getInnerContainerSize().height);
    startHeight = totalHeight;

    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    for n = 1, #crystalCost do
        local info = crystalCost[n];
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight - n * (widgetHeight + gap) - 10;
        if n == 1 then
            local line2 = findChildByName(child, "line2");
            line2:setVisible(true);
        end
        child:setPositionX(x);
        child:setPositionY(y);

        -- 初始化奖励
        child:setTag(n);
        self:initItem(child, info);

        scrollview:addChild(child);
    end
end

-- 初始化奖励项
function UIAwakeCrystalPath:initItem(grid, info)
    local classId       = info[2];
    local requireNum    = info[3];
    local ownNum        = ItemM.getAmount(ME.user, classId);
    local shortName     = ItemM.query(classId, "desc_args")["short_name"];
    local level         = ItemM.query(classId, "desc_args")["level"];

    local buyImg        = findChildByName(grid, "buy");
    local goImg         = findChildByName(grid, "go");
    local touchImg      = findChildByName(grid, "touch_bg");
    local pathLabel     = findChildByName(grid, "path_label");
    local iconImg       = findChildByName(grid, "icon");
    local nameLabel     = findChildByName(grid, "name_label");
    local countLabel    = findChildByName(grid, "count_label");

    local kerning = getLocKerning() - 3;
    if not isFullWidthLang() then
        kerning = getLocKerning() - 1;
    end

    goImg:setVisible(false);
    buyImg:setVisible(false);
    touchImg:setVisible(false);
    pathLabel:setVisible(false);
    iconImg:setVisible(true);
    nameLabel:setVisible(true);
    countLabel:setVisible(true);

    if ownNum < requireNum then
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED, false, kerning);
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
    else
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, false, kerning);
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
    end

    -- 晶核图标
    iconImg:setScale(0.6);
    iconImg:loadTexture(getItemIconPath(ItemM.query(classId, "icon")));

    -- 晶核名称及等级
    nameLabel:setString(string.format(getLocStr("awake_crystal_name"), shortName, level));
    -- 拥有数量及需求数量
    countLabel:setString(string.format("%d/%d", ownNum, requireNum));
end
